package cn.edu.hit.kg.entity;

import cn.edu.hit.CacheManager;
import cn.edu.hit.kg.data.Node;
import net.sf.json.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Reason extends BaseNode {
    public Reason(Node node) {
        super(node);
    }

    public double getRawFrequency(long faultId,String unitId){
        String freqKey = "fault_reason:" + unitId + ":" + this.getId();  //每个原因的置信度应该与机器相关
        CacheManager cacheManager = CacheManager.getInstance();
        if (cacheManager.getJedis().exists(freqKey)) {
            JSONObject freq = JSONObject.fromObject(cacheManager.getJedis().get(freqKey));
            int quantum = freq.getInt("quantum");
            int frequency = freq.optJSONObject("frequency").optInt("" + this.getId());
            return frequency * 1.0 / quantum;
        }
        else {
           return Double.parseDouble(this.getString("probability"));
        }
    }

    public double selfFrequency() {
        return Double.parseDouble("" + this.node.asMap().getOrDefault("selfFrequency","0"));
    }

    public MatchTrack trackByConclusions(Map<Long, Boolean> conclusions){
        List<ISignalMatch> nodes = BaseNode.getSubEdges(this.getId())
                .stream()
                .map(id ->  nodeCache.get(id))
                .filter(node->node instanceof ISignalMatch)
                .map(node1 -> (ISignalMatch)node1)
                .collect(Collectors.toList());
        MatchTrack track = new MatchTrack();
        track.node = this;
        track.result = ISignalMatch.MatchResultType.TRUE;
        boolean isStop = false;
        for (ISignalMatch signalMatch : nodes) {
            MatchTrack subTrack;
//            if (isStop){
//                subTrack = new MatchTrack();
//                subTrack.node = (BaseNode) signalMatch;
//                subTrack.result = ISignalMatch.MatchResultType.SKIP;
//            }else {
//                subTrack = signalMatch.trackByConclusions(conclusions);
//            }
            subTrack = signalMatch.trackByConclusions(conclusions);

            track.children.add(subTrack);
            if (!isStop && (subTrack.result== ISignalMatch.MatchResultType.TRUE)){
                isStop = true;
                track.result = ISignalMatch.MatchResultType.FALSE;
            }
        }
        return track;
    }

    public static List<Reason> listReasons(long faultId){
        return BaseNode.getAllSubNodes(faultId)
                .map(nodeCache::get)
                .filter(r -> r instanceof Reason && r.hasSubEdges()
                        && BaseNode.getSubEdges(r.getId()).stream().map(nodeCache::get).anyMatch(f->f instanceof ISignalMatch))
                .map(n->(Reason)n)
                .collect(Collectors.toList());
    }
}
